package com.sinosoft.web.common.tag;

import com.sinosoft.hydra.um.constant.BaseConstant;
import cn.com.sinux.spring.utils.JsonUtils;
import cn.com.sinux.spring.utils.ValidatorUtils;;
import org.apache.commons.lang.StringUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-9-17
 * Time: 下午1:46
 * To change this template use File | Settings | File Templates.
 */
public class JsonBuildTag extends javax.servlet.jsp.tagext.TagSupport {

    private Object value;
    private String id;


    public int doStartTag() throws JspException {
        try {
            JspWriter out = this.pageContext.getOut();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("<script>");
            if (!BaseConstant.Boolean.BOOLEAN_TRUE.equals(pageContext.getRequest().getAttribute("isInitPageContext"))) {
                pageContext.getRequest().setAttribute("isInitPageContext", BaseConstant.Boolean.BOOLEAN_TRUE);
                String uuid = UUID.randomUUID().toString();
                pageContext.getRequest().setAttribute("pageInitContextNameSpace", uuid);
                stringBuilder.append("window.pageInitContextNameSpace=\"").append(uuid).append("\"").append(";");
                stringBuilder.append("window[\"").append(uuid).append("\"]={};");
            }
            String code = (String) pageContext.getRequest().getAttribute("pageInitContextNameSpace");
            stringBuilder.append("window[\"").append(code).append("\"][\"").append(id).append("\"]=");
            if (value == null) {
                stringBuilder.append("undefined");
            } else {
                if (value instanceof String) {
                    String _val = (String) value;
                    if (StringUtils.isNotBlank(_val))
                        if (JsonUtils.isJsonString(_val) || ValidatorUtils.isNumeric(_val)) {
                            stringBuilder.append(_val);
                        } else {
                            //非数字和json，判断是一般字符串类型，需要添加双引号
                            stringBuilder.append("\"").append(_val).append("\"");
                        }
                    else
                        stringBuilder.append("undefined");
                } else {
                    stringBuilder.append(JsonUtils.toString(value));
                }
            }
            stringBuilder.append(";</script>");
            out.println(stringBuilder.toString());
        } catch (Exception e) {
            throw new JspException(e.getMessage());
        }
        return SKIP_BODY;
    }


    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }


    public void release() {
        super.release();
        this.value = null;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public void setId(String id) {
        this.id = id;
    }
}
